package org.hales.security;


import lombok.extern.slf4j.Slf4j;
import org.hales.util.DesUtil;
import org.hales.util.MD5Util;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author : Yanml
 * @date : 2022/10/19 18:07
 */
@Slf4j
public class DecodePwdAuthenticationProvider extends DaoAuthenticationProvider {

    public DecodePwdAuthenticationProvider(MyUserDetailsService userDetailsService){
        setUserDetailsService(userDetailsService);
    }


    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            this.logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            String presentedPassword = authentication.getCredentials().toString();
            //解密
            String desPassword = DesUtil.decrypt(presentedPassword);
            String md5Des = MD5Util.MD5EncodeUtf8(desPassword);
            boolean match = userDetails.getPassword().equals(md5Des); // 比较密码
            if (!match) {
                this.logger.debug("Authentication failed: password does not match stored value");
                throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        }

    }

}


